package com.unbook.filters;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.unbook.entity.ResponseVo;
import com.unbook.utils.JsonUtils;
import com.unbook.utils.JwtUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class JWTFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中令牌
        String token = request.getHeader("token");
        String msg = "";
        try {
            JwtUtils.verify(token);//验证令牌
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            msg = "无效签名";
        }catch (TokenExpiredException e){
            e.printStackTrace();
            msg = "token过期";
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            msg = "token算法不一致";
        }catch (Exception e){
            e.printStackTrace();
            msg = "token无效";
        }
        //将map 专为json  jackson
        String json = JsonUtils.toJson(ResponseVo.authErr(msg));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);//返回给前端结果
        return false;
    }
}
